import md5 from 'md5'
import axios from 'axios'

/*
 *云存储
 *文件 图片上传
 */

const request = axios.create({
  headers: {
    'Content-Type': 'multipart/form-data'
  }
})

const USER_CONFIG = {
  accessKey: 'PSdENDLCeM',
  secretKey: 'pLRzn2jbf1XG',
  bucketId: '1255428355955421186',
  expired: '90' // 过期时间
}
// 生成token
function createUploadToken (data) {
  const {
    customId,
    expired,
    fileName,
    fileSize,
    fileHash,
    customImageInfo
  } = data

  const originalSign = [
    USER_CONFIG.secretKey,
    USER_CONFIG.bucketId,
    customId,
    expired,
    fileName,
    fileSize,
    fileHash,
    customImageInfo
  ]
    .filter(Boolean)
    .join('.')

  return USER_CONFIG.accessKey + '.' + md5(originalSign)
}
/**
 * 上传文件
 * @param {object} data
 * @returns
 */
export function uploadFile (data) {
  const { file, type, customImageInfo, customId, onUploadProgress } = data
  const expiredTime = data.expiredTime || USER_CONFIG.expiredTime

  const formData = new FormData()

  formData.append('file', file)

  // 过期时间
  if (expiredTime) {
    data.append('expired', expiredTime)
  }
  // 自定义图片处理信息json字符串
  if (customImageInfo) {
    data.append('customImageInfo', customImageInfo)
  }
  if (customId) {
    data.append('customId', customId)
  }

  formData.append('bucketId', USER_CONFIG.bucketId)

  const uploadToken = createUploadToken({
    fileName: file.name,
    fileSize: file.size,
    expired: expiredTime,
    customImageInfo,
    customId
  })

  formData.append('uploadToken', uploadToken)

  let requestURL
  switch (type) {
    case 'image':
      requestURL = '/uploadImageFile'
      break
    default:
      requestURL = '/uploadSingleFile'
  }

  return request({
    data: formData,
    method: 'POST',
    url: USER_CONFIG.BASE_URL + requestURL,
    onUploadProgress
  }).then(res => {
    return new Promise(resolve => {
      const id = res.data.data.id
      const originalSign = `${USER_CONFIG.secretKey}.${id}.${USER_CONFIG.bucketId}.attachment`
      const downloadToken = `${USER_CONFIG.accessKey}.${md5(originalSign)}`

      let url
      switch (type) {
        case 'image':
          url = `${USER_CONFIG.BASE_URL}/getCustomImage?bucketId=${USER_CONFIG.bucketId}&userFileId=${id}&downloadToken=${downloadToken}&contentDisposition=attachment`
          break
        default:
          url = `${USER_CONFIG.BASE_URL}/download?bucketId=${USER_CONFIG.bucketId}&userFileId=${id}&downloadToken=${downloadToken}&contentDisposition=attachment`
      }
      // 服务端为异步、 延迟获取文件上传地址
      setTimeout(() => {
        resolve({
          url,
          id
        })
      }, 600)
    })
  })
}
